//
//  RefreshHeader.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/18.
//

import UIKit
import SnapKit
import MJRefresh

final class CTRefreshHeader: MJRefreshHeader {
    
    private lazy var loading: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView()
        if #available(iOS 13.0, *) {
            indicator.style = .medium
        } else {
            indicator.style = .white
        }
        indicator.color = .gray
        indicator.hidesWhenStopped = true
        self.addSubview(indicator)
        return indicator
    }()
    
    var isIpxTop = false
    
    var bgViewColor: UIColor? {
        didSet {
            guard let bgColor = bgViewColor else { return }
            let v = UIView().then {
                $0.backgroundColor = bgColor
            }
            self.insertSubview(v, at: 0)
            v.snp.makeConstraints { (m) in
                m.width.equalToSuperview()
                m.height.equalTo(kScreenHei)
                m.centerX.bottom.equalToSuperview()
            }
            isAutoChangeAlphaByPercent = false
        }
    }
    private var isAutoChangeAlphaByPercent = true
    override var isAutomaticallyChangeAlpha: Bool {
        get { return isAutoChangeAlphaByPercent }
        set { }
    }
    var indicatorTintColor: UIColor? {
        didSet {
            guard let c = indicatorTintColor else { return }
            loading.color = c
        }
    }
    
    override func prepare() {
        super.prepare()
        
        self.mj_h = kIsX ? 60 : 50
        loading.hidesWhenStopped = false
    }
    
    // MARK: - ********* 在这里设置子控件的位置和尺寸
    override func placeSubviews() {
        super.placeSubviews()
        loading.center = CGPoint.init(x: self.mj_w * 0.5, y: self.mj_h * 0.5)
        if isIpxTop {
            loading.centerY = kHairHei + (self.mj_h - kHairHei) * 0.5
        }
    }

    override var state: MJRefreshState {
        get {
            return super.state
        }
        set(newState) {
            if newState == state {
                return
            }
            super.state = newState
            loading.hidesWhenStopped = false
            switch state {
            case .idle:
                loading.stopAnimating()
            case .pulling:
                loading.stopAnimating()
            case .refreshing:
                loading.startAnimating()
            case .noMoreData:
                loading.hidesWhenStopped = true
                loading.stopAnimating()
            default:
                break
            }
        }
    }
}


